package test.string;

import java.util.ArrayList;
import java.util.List;

/**
 * splitLines的实现, 兼容三大平台. 经简单测试没问题, 还需继续测试更多特殊情况
 */
public class SplitLines {

    @SuppressWarnings("Duplicates")
    public static List<String> splitLinesEasy(String str) {
        List<String> strList = new ArrayList<>();
        char[] chars = str.toCharArray();
        int breakIndex = -1;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '\r') {
                int start = breakIndex + 1;
                int len = i - start;
                char[] slice = new char[len];
                System.arraycopy(chars, start, slice, 0, len);
                strList.add(String.valueOf(slice));
                breakIndex = i;
            } else if (chars[i] == '\n') {
                if (i > 0 && chars[i - 1] == '\r') {
                    breakIndex++;
                } else {
                    int start = breakIndex + 1;
                    int len = i - start;
                    char[] slice = new char[len];
                    System.arraycopy(chars, start, slice, 0, len);
                    strList.add(String.valueOf(slice));
                    breakIndex = i;
                }
            }
        }
        if (chars.length - 1 != breakIndex) {
            int len = chars.length - 1 - breakIndex;
            char[] tail = new char[len];
            System.arraycopy(chars, breakIndex + 1, tail, 0, len);
            strList.add(String.valueOf(tail));
        }
        return strList;
    }

    @SuppressWarnings("Duplicates")
    public static List<String> splitLines(String str) {
        List<String> strList = new ArrayList<>();
        char[] chars = str.toCharArray();
        int breakIndex = -1;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '\n' && i > 0 && chars[i - 1] == '\r') {
                breakIndex++;
                continue;
            }
            if (chars[i] == '\n' || chars[i] == '\r') {
                int start = breakIndex + 1;
                int len = i - start;
                char[] slice = new char[len];
                System.arraycopy(chars, start, slice, 0, len);
                strList.add(String.valueOf(slice));
                breakIndex = i;
            }
        }
        if (chars.length - 1 != breakIndex) {
            int len = chars.length - 1 - breakIndex;
            char[] tail = new char[len];
            System.arraycopy(chars, breakIndex + 1, tail, 0, len);
            strList.add(String.valueOf(tail));
        }
        return strList;
    }


    public static void main(String[] args) {
        String test = "\r\nasdf\r\njf\n898sdf\r1233123\r222\n";
        System.out.println(splitLines(test));
    }
}
